package com.jiubanqingchen.future.org.authority.user;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jiubanqingchen.future.common.enums.CacheName;
import com.jiubanqingchen.future.common.tool.TreeJson;
import com.jiubanqingchen.future.org.admin.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

public class UserAuthorityService extends BaseService {
    private static Logger logger= LoggerFactory.getLogger(UserAuthorityService.class);
    /* 缓存的菜单*/
    private static final String authorityMenus = "authorityMenus";

    /* 缓存的权限key*/
    private static final String authorityKeys = "authorityKeys";

    /**
     * 获取用户角色信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    private List<Record> getUserRole(String userId) throws Exception {
        return Db.find(Db.getSql("user.getUserRole"), userId, userId);
    }

    /**
     * 得到用户角色id数组
     *
     * @param userId
     * @return
     * @throws Exception
     */
    private String[] getUserRoleIdArray(String userId) throws Exception {
        List<Record> userRoleList = getUserRole(userId);
        if (userRoleList == null) return null;
        int len = userRoleList.size();
        String[] roleIds = new String[len];
        for (int i = 0; i < len; i++) {
            roleIds[i] = userRoleList.get(i).getStr("roleId");
        }
        return roleIds;
    }

    /**
     * 得到用户权限信息
     *
     * @param userId 用户id
     * @return
     */
    private Record getRoleAuthorityResource(String userId) throws Exception {
        String cacheName = CacheName.AUTHORITY_LIST.getValue();
        String cacheMenukey = userId + ":" + this.authorityMenus;
        String cacheKeyskey = userId + ":" + this.authorityKeys;

        //有缓存取缓存
        List<Record> authorityMenus = CacheKit.get(cacheName, cacheMenukey);
        List<String> authorityKeys = CacheKit.get(cacheName, cacheKeyskey);
        Record record = new Record().set(this.authorityMenus, authorityMenus).set(this.authorityKeys, authorityKeys);
        if (authorityMenus != null && authorityKeys != null) return record;

        //无缓存获取后存缓存
        String[] roleIds = getUserRoleIdArray(userId);
        List<Record> list = Db.template("role.getRoleAuthorityMenu", Kv.create().set("roleIds", roleIds)).find();
        authorityMenus = formatRoleAuthorityMenu(list);
        authorityKeys = getAuthorityKeys(list);

        //缓存用户菜单 和用户权限信息
        CacheKit.put(cacheName, cacheMenukey, authorityMenus);
        CacheKit.put(cacheName, cacheKeyskey, authorityKeys);
        return record.set(this.authorityMenus, authorityMenus).set(this.authorityKeys, authorityKeys);
    }

    /**
     * 格式化菜单信息
     *
     * @param menuList
     * @return
     */
    private List<Record> formatRoleAuthorityMenu(List<Record> menuList) {
        if (menuList.isEmpty()) return null;
        List<Record> formatList = new ArrayList<>();
        for (Record record : menuList) {
            if (!"MENU".equals(record.getStr("menuType"))) continue;
            Record meta = new Record();
            meta.set("icon", record.getStr("icon"));
            meta.set("title", record.getStr("title"));
            meta.set("subTitle", record.getStr("subTitle"));
            meta.set("hiddenHeaderContent", record.getBoolean("hiddenHeaderContent"));
            meta.set("keepAlive", record.getBoolean("keepAlive"));
            record.remove("icon", "title","hiddenHeaderContent", "createUser", "createTime", "updateUser", "updateTime").set("meta", meta);
            record.remove("resourceId","sortNo","menuType");
            formatList.add(record);
        }
        return new TreeJson("menuId").getTreeData(formatList, "jxhx");
    }

    /**
     * 得到用户权限key
     *
     * @param menuList
     * @return
     */
    private List<String> getAuthorityKeys(List<Record> menuList) {
        List<String> keys = new ArrayList<>();
        for (Record record : menuList) {
            String key = record.getStr("authorityKey");
            if (key != null && !"".equals(key)) keys.add(key);
        }
        keys.stream().distinct();
        return keys;
    }

    /**
     * 得到用户的权限菜单
     *
     * @param userId 用户id
     * @return
     * @throws Exception
     */
    public List<Record> getUserAuthorityMenu(String userId) throws Exception {
        return getRoleAuthorityResource(userId).get(this.authorityMenus);
    }

    /**
     * 得到用户的权限key
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public List<String> getUserAuthorityKes(String userId) throws Exception {
        return getRoleAuthorityResource(userId).get(this.authorityKeys);
    }

    /**
     * 删除当前用户的权限信息
     *
     * @param userId
     */
    public void removeAuthorityCache(String userId) {
        String cacheName = CacheName.AUTHORITY_LIST.getValue();
        String cacheMenukey = userId + ":" + this.authorityMenus;
        String cacheKeyskey = userId + ":" + this.authorityKeys;
        CacheKit.remove(cacheName, cacheMenukey);
        CacheKit.remove(cacheName, cacheKeyskey);
    }

    /**
     * 删除当前用户组的权限信息
     */
    public void removeAuthorityCaches(String[] userIds) {
        for (String userId : userIds) {
            removeAuthorityCache(userId);
        }
    }

    /**
     * 校验用户是否有操作权限
     *
     * @param userId
     * @param authorityKey
     * @return
     */
    public boolean judgeAuthority(String userId, String authorityKey) {
        try {
            return getUserAuthorityKes(userId).contains(authorityKey);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return false;
    }
}
